package controller

import (
	"gitee.com/huangxinbo/xcas/internal/app/base"
	"gitee.com/huangxinbo/xcas/internal/model"
	"gitee.com/huangxinbo/xcas/internal/service"
	"gitee.com/huangxinbo/xcas/pkg/base64_captcha"
	"gitee.com/huangxinbo/xcas/pkg/response"
	"github.com/gin-gonic/gin"
)

type CaptchaController struct {
	base    *base.Base
	captcha *base64_captcha.Captcha
	service *service.Service
}

func NewCaptchaController(base *base.Base, service *service.Service) *CaptchaController {
	captcha := base64_captcha.NewCaptcha(base.Logger, base.RedisClient)
	return &CaptchaController{
		base:    base,
		captcha: captcha,
		service: service,
	}
}

func (c *CaptchaController) RegisterRoutes(router *gin.Engine) {
	captchaGroup := router.Group("/api/captcha")
	{
		captchaGroup.POST("/generate", c.GenerateCaptcha)
	}
}

// Generate captcha
//
//	@Summary		Generate captcha
//	@Description	Generate captcha image
//	@Tags			captcha
//	@Accept			json
//	@Produce		json
//	@Param			request	body		model.CaptchaRequest	true	"captcha params"
//	@Success		200		{object}	model.CaptchaResponse	"Generate captcha"
//	@Router			/api/captcha/generate [post]
func (c *CaptchaController) GenerateCaptcha(ctx *gin.Context) {
	var req model.CaptchaRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		response.Error[any](ctx, response.INVALID_PARAMS, c.base.I18n.T("Invalid parameters"), nil)
		return
	}

	// Generate captcha
	captchaId, captchaData, err := c.captcha.GenerateCaptcha(req.Type)
	if err != nil {
		c.base.Logger.Error("Failed to generate captcha: " + err.Error())
		response.Error[any](ctx, response.ERROR, c.base.I18n.T("Failed to generate captcha"), nil)
		return
	}

	response.Success(ctx, c.base.I18n.T("Success"), model.CaptchaResponseData{
		CaptchaId:   captchaId,
		CaptchaData: captchaData,
	})
}
